package com.lzy.crm.controller;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lzy.crm.base.date.DateUtil;
import com.lzy.crm.base.page.PageQuery;
import com.lzy.crm.base.util.BootStrapReturn;
import com.lzy.crm.base.util.JsonUtil;
import com.lzy.crm.base.util.Md5Util;
import com.lzy.crm.base.util.StringUtil;
import com.lzy.crm.domain.BankCard;
import com.lzy.crm.domain.PpUser;
import com.lzy.crm.domain.ProfitRule;
import com.lzy.crm.domain.User;
import com.lzy.crm.service.BankCardService;
import com.lzy.crm.service.PpUserService;
import com.lzy.crm.service.ProfitRuleService;
import com.lzy.crm.util.BootJsonResponse;
import com.lzy.crm.util.PpUserConstants;
import com.lzy.crm.util.UserConstants;
import com.lzy.crm.vo.PlayerInfo;
import com.lzy.crm.vo.PpUserVo;


/**
 * 用户信息控制器
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/admin")
public class PpUserController {
	
	
	Logger logger= Logger.getLogger(PpUserController.class);
	
	@Resource
	private PpUserService pUserService;
	
	
	@Resource
	private ProfitRuleService profitRuleService;
	
	@Resource
	private BankCardService bankCardService;
	
	/**
	 * 用户web 端登录
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(path="/login",produces="text/html;charset=UTF-8")
	public String login(HttpServletRequest request,ModelMap model) throws Exception{
		String msg="";
		if(request.getParameter("loginNo")==null){
			return "../../login";
		}
		try {
			String loginNo = request.getParameter("loginNo").toString();
			String password =request.getParameter("password").toString();
			String mobile = request.getParameter("mobile").toString();
			String randCheckCode = request.getParameter("randCheckCode");
			
			//加入验证码
			/*Integer loginCount = request.getSession().getAttribute(UserConstants.LOGIN_COUNT)==null?1:
				(Integer) request.getSession().getAttribute(UserConstants.LOGIN_COUNT);
			request.getSession().setAttribute(UserConstants.LOGIN_COUNT, loginCount+1 );
			if(loginCount >= UserConstants.LOGIN_NUB){
				String verifyCode =(String)request.getSession().getAttribute(UserConstants.VERIFY_CODE_PREFIX);
				if(!StringUtils.equals(randCheckCode, verifyCode)){
					msg ="验证码错误";
					model.put("loginNo", loginNo);
					model.put("password", password);
					model.put("message", msg);
					return "../../login";
				}
			}*/
			
			List<PpUser> userList = null;
			userList = pUserService.getPpUserByPhone(loginNo); 
			if(userList==null||userList.size()==0){
				userList = null;// userService.getUserListByPhoneAndPwd(loginNo);
			}
			if(userList==null||userList.size()==0){
				logger.info(loginNo+": 用户名或者密码错误");
				msg ="用户名或者密码错误";
			}else if(userList.size()>1){
				logger.info(loginNo+": 登录帐号重复，请联系管理员");
				msg ="登录帐号重复，请联系管理员";
			}else{
				PpUser user = userList.get(0);
				/*if(StringUtil.equals(Md5Util.encode("123456"), user.getPwd())){
					logger.info(loginNo+": 请在公众号修改默认密码 123456 ，即可登陆~~ ");
					msg =" 请在郴州互娱公众号菜单 代理后台 修改默认密码 123456 ，即可登陆~~ ";
				}else*/ if(StringUtil.equals(Md5Util.encode(password), user.getPwd())){
					if(user.getFreeze()==PpUserConstants.USER_STATUS_NORMAL){
						// 登录成功
						model.put("user", user);
						// 登录信息 写入session
						request.getSession().setMaxInactiveInterval(1800);  // 30 分钟失效
						request.getSession().setAttribute("userSession", user);
						request.getSession().setAttribute(UserConstants.LOGIN_COUNT, 0 );
						
						if(StringUtil.equals("1", mobile)){
							return "redirect:index_mobile.html"; // 手机端
						}else{
							return "redirect:index.html"; //  PC端
						}
					}else if(user.getFreeze()== PpUserConstants.USER_STATUS_LOCK){
						logger.info(loginNo+": 帐号未激活，请联系管理员");
						msg ="帐号已被锁定，请联系管理员";
					}else{
						logger.info(loginNo+": 帐号已被注销");
						msg ="账号已封禁，请联系管理员~";
					}
				}else{
					logger.info(loginNo+": 用户名或者密码错误");
					msg ="用户名或者密码错误";
				}
			}
		} catch (Exception e) {
			logger.error("登录出错", e);
		}
		model.put("message", msg);
		return "../../login";
	}
	
	
	
	
	
	
	
	/**
	 * 退出登录
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/logout")  
	public String logout(HttpServletRequest request,ModelMap model) {
		request.getSession().removeAttribute("userSession");
		return "../../login";
	}
	
	
	
	/**
	 * 主页面
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/index_mobile")  
	public String indexMobile() {
		return "mobile/index";
	}
	
	
	/**
	 * 代理商主界面
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/user_main_mobile")  
	public String userMian(HttpServletRequest request,ModelMap model) {
		PpUser user = (PpUser)request.getSession().getAttribute("userSession");
		model.put("addAgent", 1);
		return "mobile/ppuser/user_main";
	}
	
	
	
	/**
	 * 用户管理模块
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/user_manage_mobile")  
	public String mobileCard(HttpServletRequest request,ModelMap model) {
		try {
			PpUser user = (PpUser)request.getSession().getAttribute("userSession");
		} catch (Exception e) {
			logger.error("用户管理模块", e);
		}
		return "mobile/ppuser/manage_menu";
	}
	
	
	/**
	 * 用户管理模块
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/game_manage_mobile")  
	public String game_menu(HttpServletRequest request,ModelMap model) {
		try {
			PpUser user = (PpUser)request.getSession().getAttribute("userSession");
		} catch (Exception e) {
			logger.error("用户管理模块", e);
		}
		return "mobile/ppuser/game_menu";
	}
	
	/**
	 * 添加代理商
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/user_add_mobile")  
	public String userAddMobile(HttpServletRequest request,ModelMap model){
		PpUser user = (PpUser)request.getSession().getAttribute("userSession");
		String prifitLevel = user.getUserLevel()!=null?user.getUserLevel().toString():null;
		if(user.getRid().compareTo( PpUserConstants.USER_TYPE_MANAGE)==-1){
			prifitLevel=null;
		}
		List<ProfitRule> profitRule = profitRuleService.getProfitRuleList(null, prifitLevel);
		model.put("profitRule", profitRule);
		return "mobile/ppuser/user_add";
	}
	
	
	
	
	
	
	
	
	/**
	 * 添加下级代理
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(path="/user_save",method=RequestMethod.POST,produces="text/html;charset=UTF-8")
	@ResponseBody
	public String userSave(HttpServletRequest request, 
			ModelMap model) {
		BootJsonResponse response=new BootJsonResponse();
		try{
			PpUser user = (PpUser)request.getSession().getAttribute("userSession");
			String uid = request.getParameter("uid");
			String realname = request.getParameter("realname");
			String uphone = request.getParameter("uphone");
			String pwd = request.getParameter("pwd");
			String code = request.getParameter("code");
			String wechat = request.getParameter("wechat");
			String userLevel = request.getParameter("userLevel");
			
			PpUser newUser = pUserService.getPpUser(uid);
			
			if(newUser.getRid()==PpUserConstants.USER_TYPE_AGENT && user.getRid()==PpUserConstants.USER_TYPE_AGENT){
				response.setStatusCode(BootJsonResponse.STATUS_CODE_FAILURE);
				response.setMessage("该用户已是代理商");
				return JsonUtil.toJson(response) ;
			}
			
			if((uphone==null||StringUtil.equals(uphone, ""))){
				response.setStatusCode(BootJsonResponse.STATUS_CODE_FAILURE);
				response.setMessage("手机不能同时为空");
				return JsonUtil.toJson(response) ;
			}else{
				List<PpUser> phoneList = pUserService.getPpUserByPhone(uphone);
				if(phoneList.size()>0){
					if(!StringUtil.equals(phoneList.get(0).getUnionid(), newUser.getUnionid())&&
							phoneList.size()!=1){
						response.setStatusCode(BootJsonResponse.STATUS_CODE_FAILURE);
						response.setMessage("手机号码已被占用，请换一个手机号码 ");
						return JsonUtil.toJson(response) ;
					}
				}
				
				List<PpUser> newUserList = pUserService.getPpUserByCode(code);
				if(	newUserList.size()>1 || (newUserList.size()>0&&newUserList.get(0).getUid()!=newUser.getUid())){
					model.put("statusCode",BootJsonResponse.STATUS_CODE_FAILURE);
					model.put("message","邀请码已被占用~");
					return JsonUtil.toJson(model) ;
				}
				
				// 非管理员 靓号判断
				if(user.getRid()!=PpUserConstants.USER_TYPE_MANAGE){
					String codes ="66666-88888-16666-18888-66688-66888-11888-11666-16888-99999";
					if(codes.indexOf(code)!=-1){
						model.put("statusCode",BootJsonResponse.STATUS_CODE_FAILURE);
						model.put("message","邀请码已被占用~");
						return JsonUtil.toJson(model) ;
					}
				}
				
				newUser.setFrontUid(user.getUid());
				newUser.setRealname(realname);
				newUser.setUphone(uphone);
				newUser.setPwd(Md5Util.encode(pwd));
				newUser.setCode(Integer.parseInt(code));
				newUser.setWechat(wechat);
				newUser.setUserLevel(Integer.parseInt(userLevel));
				newUser.setRid(PpUserConstants.USER_TYPE_AGENT);
				pUserService.updateByPrimaryKeySelective(newUser);
				response.setStatusCode(BootJsonResponse.STATUS_CODE_SUCCESS);
				response.setMessage("添加成功");
			}
		}catch(Exception e){
			response.setStatusCode(BootJsonResponse.STATUS_CODE_FAILURE);
			response.setMessage("添加失败，请与管理员联系");
			logger.error("添加代理商失败", e);
		}
		return JsonUtil.toJson(response) ;
	}
	
	
	
	@RequestMapping(path="/query_user",method=RequestMethod.POST,produces="text/html;charset=UTF-8")
	@ResponseBody
	public String query_user(HttpServletRequest request, 
			ModelMap model) {
		try{
			String uid = request.getParameter("uid");
			String code = request.getParameter("code");

			PpUser newUser = pUserService.getPpUser(uid);
			List<PpUser> newUserList = pUserService.getPpUserByCode(code);
			if(newUser==null ){
				model.put("statusCode",BootJsonResponse.STATUS_CODE_FAILURE);
				model.put("message","查询用户信息为空~");
				return JsonUtil.toJson(model) ;
			}
			if(	newUserList.size()>1 || (newUserList.size()>0&&newUserList.get(0).getUid()!=newUser.getUid())){
				model.put("statusCode",BootJsonResponse.STATUS_CODE_FAILURE);
				model.put("message","邀请码已被占用~");
				return JsonUtil.toJson(model) ;
			}
			model.put("playerName", newUser.getNickname());
			model.put("statusCode",BootJsonResponse.STATUS_CODE_SUCCESS);
			model.put("message","添加成功");
		}catch(Exception e){
			model.put("statusCode",BootJsonResponse.STATUS_CODE_FAILURE);
			model.put("message","添加失败，请与管理员联系");
			logger.error("查询玩家失败", e);
		}
		return JsonUtil.toJson(model) ;
	}
	
	/**
	 * 我的推广员
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/user_next_info_mobile")  
	public String userNextInfo_mobile(HttpServletRequest request,ModelMap model) {
		return "mobile/ppuser/user_next_agent";
	}
	
	
	/**
	 * 我的推广员 数据
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(path="/user_next_info_data",method=RequestMethod.POST,produces="text/html;charset=UTF-8")
	@ResponseBody
	public String userNextInfoData(HttpServletRequest request, @RequestParam Map<String, String> form,
			ModelMap model) {
		BootStrapReturn<PpUserVo> result = new BootStrapReturn<PpUserVo>();
		try {
			PpUser user = (PpUser)request.getSession().getAttribute("userSession");
			String phone = request.getParameter("phone");
			String code =request.getParameter("code");
			Integer currentPage = Integer.parseInt(request.getParameter("numPerPage"));
			Integer numPerPage = Integer.parseInt(request.getParameter("pageNum"));
			PageQuery pageQuery = new PageQuery(numPerPage,currentPage);
			pageQuery.setIsQueryTotal(true); 
			List<PpUserVo>  puserList = pUserService.getNextUserList(user.getUid(), code, phone, null, null, null, pageQuery);
			result.setPage(pageQuery.getPageIndex());
			result.setTotal(pageQuery.getTotalCount());
			result.setRows(puserList);
		} catch (Exception e) {
			logger.error("推广员列表", e);
		}
		return JsonUtil.toJson(result) ;
	}
	
	
	/**
	 *  用户查询
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/user_parent_mobile")  
	public String usersParentMobile(HttpServletRequest request,ModelMap model) {
		return "mobile/ppuser/user_parent";
	}
	
	/**
	 *  用户查询数据补充
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(path="/user_parent_mobile_data",method=RequestMethod.POST,produces="text/html;charset=UTF-8")
	@ResponseBody
	public String userParentData(HttpServletRequest request, @RequestParam Map<String, String> form,
			ModelMap model) {
		BootStrapReturn<PpUserVo> result = new BootStrapReturn<PpUserVo>();
		try {
			PpUser user = (PpUser)request.getSession().getAttribute("userSession");
			String uid = request.getParameter("uid");
			String uphone = request.getParameter("uphone");
			String code =request.getParameter("code");
			String realname =request.getParameter("realname");
			String user_level =request.getParameter("user_level");
			Integer currentPage = Integer.parseInt(request.getParameter("numPerPage"));
			Integer numPerPage = Integer.parseInt(request.getParameter("pageNum"));
			PageQuery pageQuery = new PageQuery(numPerPage,currentPage);
			pageQuery.setIsQueryTotal(true); 
			
			// 查询下级的玩家
			List<PpUserVo>  puserList = pUserService.getNextUserList(user.getUid(), code, uphone, uid, realname, user_level, pageQuery);
			result.setPage(pageQuery.getPageIndex());
			result.setTotal(pageQuery.getTotalCount());
			result.setRows(puserList);
		} catch (Exception e) {
			logger.error("用户列表", e);
		}
		return JsonUtil.toJson(result) ;
	}
	
	
	
	
	/**
	 * 个人信息界面
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/user_info_mobile")  
	public String userInfoMobile(HttpServletRequest request,ModelMap model) {
		try {
			PpUser user = (PpUser) request.getSession().getAttribute("userSession");
			
			PpUser  newUser = pUserService.getPpUser(user.getUid().toString());
			
			String yesterday = DateUtil.formatDateWithoutTime(DateUtil.getNextDay(new Date()));
			
			String startTime = yesterday +" 00:00:00" ;
			String entTime = yesterday +" 23:59:59";
			
			// 父级信息
			PpUser parentUser = pUserService.getPpUser(user.getFrontUid().toString());
			
			
			// 剩余房卡
			
			
			// 近15日分润汇总
			//String towWeek =DateUtil.formatDateWithoutTime(DateUtil.getCountDay(new Date(), -15));
			ProfitRule profitRule = profitRuleService.getById(newUser.getUserLevel());
			model.put("profitRule", profitRule);
			model.put("user", newUser);
			model.put("parentUser", parentUser);
		} catch (Exception e) {
			logger.error("个人信息界面", e);
		}
		return "mobile/ppuser/user_info";
	}
	
	
	
	
	
	
	

	/**
	 *  推广员查询超管
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/user_agent_admin_mobile")  
	public String user_agent_admin_mobile(HttpServletRequest request,ModelMap model) {
		return "mobile/ppuser/user_agent_admin_mobile";
	}
	/**
	 *  推广员数据补充
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(path="/user_agent_admin_mobile_data",method=RequestMethod.POST,produces="text/html;charset=UTF-8")
	@ResponseBody
	public String user_agent_admin_mobileDate(HttpServletRequest request, @RequestParam Map<String, String> form,
			ModelMap model) {
		BootStrapReturn<PpUserVo> result = new BootStrapReturn<PpUserVo>();
		try {
			PpUser user = (PpUser)request.getSession().getAttribute("userSession");
			String uid = request.getParameter("uid");
			String realname =request.getParameter("realname");
			String uphone =request.getParameter("uphone");
			String code =request.getParameter("code");
			
			Integer currentPage = Integer.parseInt(request.getParameter("numPerPage"));
			Integer numPerPage = Integer.parseInt(request.getParameter("pageNum"));
			PageQuery pageQuery = new PageQuery(numPerPage,currentPage);
			pageQuery.setIsQueryTotal(true); 
			List<PpUserVo>  puserList = pUserService.getNextUserList(user.getUid(), code, uphone, uid, realname, null, pageQuery);
			result.setPage(pageQuery.getPageIndex());
			result.setTotal(pageQuery.getTotalCount());
			result.setRows(puserList);
		} catch (Exception e) {
			logger.error("推广员列表", e);
		}
		return JsonUtil.toJson(result) ;
	}
	
	
	
	
	
	/**
	 *  用户查询 超管
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/user_list_admin_mobile")  
	public String user_list_admin_mobile(HttpServletRequest request,ModelMap model) {
		return "mobile/ppuser/user_list_admin";
	}
	
	/**
	 *  用户查询 超管 数据补充
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(path="/user_list_admin_mobile_data",method=RequestMethod.POST,produces="text/html;charset=UTF-8")
	@ResponseBody
	public String user_list_admin_mobileData(HttpServletRequest request, @RequestParam Map<String, String> form,
			ModelMap model) {
		BootStrapReturn<PpUserVo> result = new BootStrapReturn<PpUserVo>();
		try {
			PpUser user = (PpUser)request.getSession().getAttribute("userSession");
			String uid = request.getParameter("uid");
			String uphone = request.getParameter("uphone");
			String code =request.getParameter("code");
			String realname =request.getParameter("realname");
			String user_level =request.getParameter("user_level");
			Integer currentPage = Integer.parseInt(request.getParameter("numPerPage"));
			Integer numPerPage = Integer.parseInt(request.getParameter("pageNum"));
			PageQuery pageQuery = new PageQuery(numPerPage,currentPage);
			pageQuery.setIsQueryTotal(true); 
			
			// 
			List<PpUserVo>  puserList = pUserService.getUserList(code, uphone, uid, realname, user_level, pageQuery);
			result.setPage(pageQuery.getPageIndex());
			result.setTotal(pageQuery.getTotalCount());
			result.setRows(puserList);
		} catch (Exception e) {
			logger.error("用户列表", e);
		}
		return JsonUtil.toJson(result) ;
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	/**
	 * 超级管理员信息界面
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/user_admin_info_mobile")  
	public String userAdminInfoMobile(HttpServletRequest request,ModelMap model) {
		try {
			PpUser user = (PpUser)request.getSession().getAttribute("userSession");
			/*User newUser = userService.getById(user.getId());
			// 总共转出卡数
			Integer totalCard = cardFlowService.getCardinflow(newUser.getGameUserId(), null, null);
			// 昨日转出卡数
			String yesterday = DateUtil.formatDateWithoutTime(DateUtil.getNextDay(new Date()));
			String startTime = yesterday +" 00:00:00" ;
			String entTime = yesterday +" 23:59:59";
			Integer yesterdayCard = cardFlowService.getCardinflow(newUser.getGameUserId(), startTime, entTime);
			
			// 昨日充值统计
			OrderStatVo yesterdayrderStatVo = orderService.getOrderStatVo(null, "1", startTime, entTime);
			// 累积充值
			OrderStatVo allrderStatVo = orderService.getOrderStatVo(null, "1", null, null);
			// 近15日充值
			String towWeek =DateUtil.formatDateWithoutTime(DateUtil.getCountDay(new Date(), -15));
			OrderStatVo twoWeekorderStatVo = orderService.getOrderStatVo(null, "1", towWeek, null);
			
			PlayerInfo playerInfo=userService.getPlayerInfo(user.getGameUserId(), null);
			if(playerInfo!=null){
				model.put("playerTotalCard", playerInfo.getInsureScore());
				if(newUser.getGameUserId()==null||newUser.getGameUserId()!=playerInfo.getGameId()){
					newUser.setGameUserId(playerInfo.getGameId());
					newUser.setAgentId(playerInfo.getGameId());
					userService.updateByPrimaryKeySelective(newUser);
				}
			}
			// 近15日分润汇总
			Integer profitFee = profitService.getProfitStat(user.getId(), towWeek, null);
			ProfitRule profitRule = profitRuleService.getById(newUser.getUserLevel());
			model.put("profitRule", profitRule);
			model.put("profitFee", profitFee);
			model.put("yesterdayrderStatVo", yesterdayrderStatVo);
			model.put("allrderStatVo", allrderStatVo);
			model.put("twoWeekorderStatVo", twoWeekorderStatVo);
			model.put("totalCard", totalCard);
			model.put("yesterdayCard", yesterdayCard);
			model.put("user", newUser);*/
		} catch (Exception e) {
			logger.error("个人信息界面", e);
		}
		return "mobile/user/user_admin_info";
	}
	
	
	/**
	 * 修改密码页面
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/updatepwd_mobile")  
	public String updatepwdMobile(HttpServletRequest request,ModelMap model) {
		PpUser user = (PpUser)request.getSession().getAttribute("userSession");
		model.put("user", user);
		return "mobile/ppuser/user_edit_pwd";
	}
	
	/**
	 * 添加银行卡页面
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/update_bank_mobile")  
	public String updateBankMobile(HttpServletRequest request,ModelMap model) {
		PpUser user = (PpUser)request.getSession().getAttribute("userSession");
		model.put("user", user);
		try {
			List<BankCard> bankCardList =bankCardService.getBankCardListByUserId(user.getUid()+"");
			if(bankCardList!=null&&bankCardList.size()>0){
				model.put("bankCard", bankCardList.get(0));
			}
		} catch (Exception e) {
			logger.error("查询银行卡错误", e);
		}
		return "mobile/ppuser/user_edit_bank";
	}
	
	
	@RequestMapping(path="/update_bank_save_mobile",method=RequestMethod.POST,produces="text/html;charset=UTF-8")
	@ResponseBody
	public String saveBank(HttpServletRequest request,@RequestParam Map<String, String> form,ModelMap model) {
		BootJsonResponse response=new BootJsonResponse();
		try {
			String bankName = form.get("bankName");
			String bankUserNo = form.get("bankUserNo");
			String bankUserName = form.get("bankUserName");
			PpUser user = (PpUser)request.getSession().getAttribute("userSession");
			BankCard bankCard = new BankCard();
			
			List<BankCard> bankCardList =bankCardService.getBankCardListByUserId(user.getUid()+"");
			if(bankCardList!=null&&bankCardList.size()>0){
				bankCard = bankCardList.get(0);
				bankCard.setBankName(bankName);
				bankCard.setBankUserNo(bankUserNo);
				bankCard.setBankUserName(bankUserName);
				bankCard.setUpdateTime(new Date());
				bankCardService.updateByPrimaryKeySelective(bankCard);
			}else{
				bankCard.setUserId(user.getUid());
				bankCard.setBankName(bankName);
				bankCard.setBankUserNo(bankUserNo);
				bankCard.setBankUserName(bankUserName);
				bankCard.setCardFlag("1"); // 默认启用
				bankCard.setCreateTime(new Date());
				bankCardService.insertSelective(bankCard);
			}
			
			response.setStatusCode(BootJsonResponse.STATUS_CODE_SUCCESS);
			response.setMessage("操作成功~");
		} catch (Exception e) {
			logger.error(" 添加银行卡信息 ", e);
			response.setStatusCode(BootJsonResponse.STATUS_CODE_FAILURE);
			response.setMessage(" 系统错误，请联系管理员 ");
		}
		return JsonUtil.toJson(response);
	}
	
	
	/**
	 * 用户列表(超管权限)
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/user_list_mobile")  
	public String usersListMobile(HttpServletRequest request,ModelMap model) {
		PpUser puser = (PpUser)request.getSession().getAttribute("userSession");
		if(puser.getRid() == PpUserConstants.USER_TYPE_MANAGE){
			return "mobile/user/user_list";
		}
		return "mobile/user/user_next_info";
	}
	
	/**
	 * 用户列表(超管权限)
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/user_list_apply_mobile")  
	public String usersListApplyMobile(HttpServletRequest request,ModelMap model) {
		PpUser user = (PpUser)request.getSession().getAttribute("userSession");
		if(user.getRid()== PpUserConstants.USER_TYPE_MANAGE){
			return "mobile/user/user_list_apply";
		}
		return "mobile/user/user_next_info";
	}
	
	
	

	
	@RequestMapping("/user_up_parent_mobile")  
	public String usersUpParentMobile(HttpServletRequest request,ModelMap model) {
		return "mobile/user/user_up_parent";
	}
	
	
	
	/**
	 * 个人信息保存
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(path="/user_edit_password",method=RequestMethod.POST,produces="text/html;charset=UTF-8")
	@ResponseBody
	public String doEditUserPassword(HttpServletRequest request,ModelMap model) {
		BootJsonResponse bootJsonResponse =new BootJsonResponse();
		try {
			PpUser user = (PpUser)request.getSession().getAttribute("userSession");
			if( user.getRid()== PpUserConstants.USER_TYPE_MANAGE){
				bootJsonResponse.setStatusCode(BootJsonResponse.STATUS_CODE_FAILURE);
				bootJsonResponse.setMessage(" 权限不够，请联系管理员 ");
				return JsonUtil.toJson(bootJsonResponse); 
			}
			String userId =request.getParameter("userId");
			/*User newUser=userService.getById(userId);
			newUser.setPassword(Md5Util.encode("123456"));
			userService.updateByPrimaryKeySelective(newUser);*/
			bootJsonResponse.setMessage("操作成功");
			bootJsonResponse.setStatusCode(BootJsonResponse.STATUS_CODE_SUCCESS);
		} catch (Exception e) {
			bootJsonResponse.setMessage("操作失败，请联系管理员");
			bootJsonResponse.setStatusCode(BootJsonResponse.STATUS_CODE_FAILURE);
			logger.error("修改个人信息失败", e);
		}
		return JsonUtil.toJson(bootJsonResponse);
	}
	
	
	
	
	/**
	 * 玩家列表(超管权限)
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/user_player_list_mobile")  
	public String userPlayerListMobile(HttpServletRequest request,ModelMap model) {
		return "mobile/user/user_player_list";
	}
	
	/**
	 * 超管玩家列表
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(path="/user_player_mobile_data",method=RequestMethod.POST,produces="text/html;charset=UTF-8")
	@ResponseBody
	public String userPlayerData(HttpServletRequest request, @RequestParam Map<String, String> form,
			ModelMap model) {
		BootStrapReturn<PpUser> result = new BootStrapReturn<PpUser>();
		try {
			String gameId = request.getParameter("gameId");
			Integer currentPage = Integer.parseInt(request.getParameter("numPerPage"));
			Integer numPerPage = Integer.parseInt(request.getParameter("pageNum"));
			PageQuery pageQuery = new PageQuery(numPerPage,currentPage);
			pageQuery.setIsQueryTotal(true); 
			Integer parentId =null;
			Integer upParentId =null;
			/*List<User> playerUserList = userService.getAllPlayerUserList(parentId, upParentId, gameId,pageQuery);
			for (User user : playerUserList) {
				if(user.getParentId()!=null&&user.getParentId()!= 0){
					User puser= userService.getById(user.getParentId());
					user.setParentId(puser.getGameUserId());
				}
			}*/
			result.setPage(pageQuery.getPageIndex());
			result.setTotal(pageQuery.getTotalCount());
			//result.setRows(playerUserList);
		} catch (Exception e) {
			logger.error("代理列表", e);
		}
		return JsonUtil.toJson(result) ;
	}
	
	
	
	
	
	
	/**
	 * 个人信息保存
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(path="/user_edit_parentId",method=RequestMethod.POST,produces="text/html;charset=UTF-8")
	@ResponseBody
	public String doEditUserParentId(HttpServletRequest request,ModelMap model) {
		BootJsonResponse bootJsonResponse =new BootJsonResponse();
		try {
			PpUser user = (PpUser)request.getSession().getAttribute("userSession");
			if(user.getRid()==PpUserConstants.USER_TYPE_MANAGE){
				bootJsonResponse.setStatusCode(BootJsonResponse.STATUS_CODE_FAILURE);
				bootJsonResponse.setMessage(" 权限不够，请联系管理员 ");
				return JsonUtil.toJson(bootJsonResponse); 
			}
			String userId =request.getParameter("userId");
			String pgameId = request.getParameter("pgameId");
			if(StringUtil.isEmpty(pgameId)){
				bootJsonResponse.setMessage("邀请人游戏ID不能为空~");
				bootJsonResponse.setStatusCode(BootJsonResponse.STATUS_CODE_FAILURE);
				return JsonUtil.toJson(bootJsonResponse);
			}
			/*User newUser=userService.getById(userId);
			
			// 判断是否被占用
			User gameUser = userService.getUserInfoByGameid(pgameId);
			if(gameUser==null){
				bootJsonResponse.setMessage("绑定的玩家信息为空~");
				bootJsonResponse.setStatusCode(BootJsonResponse.STATUS_CODE_FAILURE);
				return JsonUtil.toJson(bootJsonResponse);
			}
			if( gameUser.getGameUserId()==Integer.valueOf(pgameId)){
				bootJsonResponse.setMessage("已经绑定次玩家，切勿重新绑定~");
				bootJsonResponse.setStatusCode(BootJsonResponse.STATUS_CODE_FAILURE);
				return JsonUtil.toJson(bootJsonResponse);
			}
			newUser.setParentId(gameUser.getId());
			gameUser.setParentNub(newUser.getParentNub()+1);
			if(gameUser.getParentId()!=null&&gameUser.getParentId()!=0){
				newUser.setUpParentId(gameUser.getParentId());
				// 修改下属父ID
				List<User> userList =userService.getUserListByParentId(newUser.getId());
				gameUser.setUpParentNub(newUser.getUpParentNub()+userList.size());
				for (User  suser : userList) {
					suser.setUpParentId(gameUser.getId());
					userService.updateByPrimaryKeySelective(suser);
				}
			}
			
			userService.updateByPrimaryKeySelective(newUser);
			userService.updateByPrimaryKeySelective(gameUser);
			bootJsonResponse.setMessage("操作成功");
			bootJsonResponse.setStatusCode(BootJsonResponse.STATUS_CODE_SUCCESS);*/
		} catch (Exception e) {
			bootJsonResponse.setMessage("操作失败，请联系管理员");
			bootJsonResponse.setStatusCode(BootJsonResponse.STATUS_CODE_FAILURE);
			logger.error("修改个人信息失败", e);
		}
		return JsonUtil.toJson(bootJsonResponse);
	}
	
	
	// 超管修改代理商信息
	@RequestMapping("/query_agent_user_info")
	public String queryAgentUserInfo(HttpServletRequest request,ModelMap model) {
		try {
			PpUser sessionUser = (PpUser)request.getSession().getAttribute("userSession");
			String id = request.getParameter("userId");
			/*User user = userService.getById(id);
			if(user!=null){
				user.setPassword(null);
				model.put("user", user);
			}
			String prifitLevel = user.getUserType();
			if(StringUtil.equals(sessionUser.getUserType(), UserConstants.USER_TYPE_MANAGE)){
				prifitLevel=null;
			}
			List<ProfitRule> profitRule = profitRuleService.getProfitRuleList(null, prifitLevel);*/
			//model.put("profitRule", profitRule);
		} catch (Exception e) {
			logger.error("用户信息", e);
		}
		return "mobile/user/user_edit";
	}
	
	
	/**
	 * 修改密码
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(path="/updatepwd_save",method=RequestMethod.POST,produces="text/html;charset=UTF-8")
	@ResponseBody
	public String doUpdatepwd(HttpServletRequest request,ModelMap model) {
		BootJsonResponse bootJsonResponse =new BootJsonResponse();
		try {
			String newPwd = request.getParameter("newPassword");
			String oldPwd = request.getParameter("oldPassword");
			PpUser user = (PpUser)request.getSession().getAttribute("userSession");
			PpUser newUser =pUserService.getPpUser(user.getUid()+"");
			if(StringUtil.equals(Md5Util.encode(oldPwd), newUser.getPwd())){
				user.setPwd(Md5Util.encode(newPwd));
				pUserService.updateByPrimaryKeySelective(user);
				bootJsonResponse.setMessage("操作成功");
				bootJsonResponse.setStatusCode(BootJsonResponse.STATUS_CODE_SUCCESS);
			}else{
				// 旧密码输入错误
				bootJsonResponse.setMessage("旧密码输入错误");
				bootJsonResponse.setStatusCode(BootJsonResponse.STATUS_CODE_FAILURE);
			}
		} catch (Exception e) {
			bootJsonResponse.setMessage("系统异常，请联系管理员");
			bootJsonResponse.setStatusCode(BootJsonResponse.STATUS_CODE_FAILURE);
			logger.error("修改密码失败", e);
		}
		return JsonUtil.toJson(bootJsonResponse);
	}
	
	/**
	 * 添加代理商
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/user_add_card_mobile")  
	public String user_add_card_mobile(HttpServletRequest request,ModelMap model){
		PpUser user = (PpUser)request.getSession().getAttribute("userSession");
		PpUser puser=pUserService.getById(user.getUid());
		model.put("user", puser);
		return "mobile/ppuser/user_add_card";
	}
	
	
	/**
	 * 充饭卡
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(path="/pcard_add_mobile",method=RequestMethod.POST,produces="text/html;charset=UTF-8")
	@ResponseBody
	public String card_list_mobile(HttpServletRequest request,ModelMap model) {
		try{
			String gameId =request.getParameter("gameId");
			PpUser puser=pUserService.getById(gameId);
			if(puser!=null){
				model.put("playerInfo", puser);
			}
			model.put("statusCode", BootJsonResponse.STATUS_CODE_SUCCESS);
		}catch(Exception e){
			logger.error("查询单个玩家错误", e);
			model.put("statusCode", BootJsonResponse.STATUS_CODE_FAILURE);
		}
		return JsonUtil.toJson(model);
		
	} 

	
	
	
	/**
	 * 给玩家添加房卡
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(path="/card_add_save",method=RequestMethod.POST,produces="text/html;charset=UTF-8")
	@ResponseBody
	public String cardSave(HttpServletRequest request, 
			ModelMap model) {
		BootJsonResponse response=new BootJsonResponse();
		try{
			Integer gameId = Integer.parseInt(request.getParameter("gameId")); // 玩家ID
			Integer userId = Integer.parseInt(request.getParameter("userId")); // 玩家ID
			Integer function = Integer.parseInt( request.getParameter("func"));  			 // 玩家购买的套餐
			Integer card = Integer.parseInt(request.getParameter("card"));  			 // 玩家购买的卡数
			Integer awardCard = Integer.parseInt(request.getParameter("awardCard"));    //赠玩家的卡数
			String remark = request.getParameter("remark");  		 //备注
			String buyCardGroupId = request.getParameter("buyCardGroupId"); 
			if(StringUtil.equals("1", buyCardGroupId)){
				// 套餐购买方案
				if(1== function){
					card = 1; awardCard=0;
				}else if(13==function){
					card = 12; awardCard=1;
				}else if(40== function){
					card = 36; awardCard=4;
				}else if(90 == function){
					card = 80; awardCard=10;
				}else if(180 ==function){
					card = 160; awardCard=20;
				} 
			}else{
				function=null;
			}
			if(userId==null||card==null||(0<=card&&10000<card)||(0<=awardCard&&10000<awardCard)){
				response.setStatusCode(BootJsonResponse.STATUS_CODE_FAILURE);
				response.setMessage("请填写正确的购买信息");
				return JsonUtil.toJson(response) ;
			}else{
				
					
					PpUser user = (PpUser)request.getSession().getAttribute("userSession");
					String result = "";
					// 代理商添加房卡
					result = pUserService.newBuyCard(user, gameId, card);
					if(StringUtil.equals("01", result)){
						response.setStatusCode(BootJsonResponse.STATUS_CODE_SUCCESS);
						response.setMessage("充卡成功");
					}else if(StringUtil.equals("03", result)){
						response.setStatusCode(BootJsonResponse.STATUS_CODE_FAILURE);
						response.setMessage("代理商信息有误，请联系管理员");
					}else if(StringUtil.equals("04", result)){
						response.setStatusCode(BootJsonResponse.STATUS_CODE_FAILURE);
						response.setMessage("玩家信息有误，请联系管理员");
					}else if(StringUtil.equals("02", result)){
						response.setStatusCode(BootJsonResponse.STATUS_CODE_FAILURE);
						response.setMessage("房卡不足，请先充值房卡");
					}
			}
		}catch(Exception e){
			logger.error("给玩家充值房卡失败", e);
			response.setStatusCode(BootJsonResponse.STATUS_CODE_FAILURE);
			response.setMessage("系统错误，请联系管理员");
			return JsonUtil.toJson(response) ;
		}
		return JsonUtil.toJson(response) ;
	}
}
